<template>
  <div>
    <el-main>
      <el-row :gutter="20">
        <el-col :span="2">
          <div v-if="is_admin_view == 0">
            <el-button type="primary" @click='AddCertificate' style="width:100%">添加证书</el-button>
          </div>
        </el-col>
        <el-col :span="3">
          <el-select v-model="value1" placeholder="请选择类型" clearable @change="getList">
            <el-option v-for="item in options1" :key="item.value" :label="item.type" :value="item.type">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select v-model="value2" placeholder="请选择有效期" clearable @change="getList">
            <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <div>
        <el-table style="width:90%" :header-cell-style="{ background: '#F3F8FE' }" @row-click="rowClick" align="center"
          :data="ListArr" border class="tableHeight">
          <el-table-column align="center" prop="number" label="证书编号">
          </el-table-column>
          <el-table-column align="center" prop="name" width="380" label="证书名称">
          </el-table-column>
          <el-table-column align="center" prop="type" label="证书类型">
          </el-table-column>
          <el-table-column align="center" prop="term_time" label="证书有效日期">
          </el-table-column>
          <el-table-column align="center" prop="term_time" label="是否过期">
            <template slot-scope="scope">
              <el-tag v-if="Date.parse(new Date(scope.row.term_time)) < new Date().getTime()" type="danger">已过期</el-tag>
              <el-tag v-else type="success">未过期</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button class="see" @click="see(scope.row.id)" type="text">查看</el-button>
              <el-button class="see" @click="set(scope.row.id)" type="text">修改</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @confirm="deleteUser(scope.row.id)">
                <el-button slot="reference" class="delete" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination" style="width:90%">
          <el-pagination background @current-change="handleCurrentChange" :current-page="page" :page-size="limit"
            layout="total, prev, pager, next, jumper" :total="count" align='left'></el-pagination>
        </div>
      </div>
    </el-main>


    <el-dialog destroy-on-close :close-on-click-modal='false' :title="dialogTypeTitle[dialogType]"
      :visible.sync="dialogVisible" @close="cancelAdd" width="40%" :before-close="handleClose">
      <el-form ref="form" :model="add" label-width="120px">
        <el-form-item label="证书编号">
          <el-input v-model="add.num" :disabled="dialogType == 2 ? true : false"></el-input>
        </el-form-item>
        <el-form-item label="证书名称">
          <el-input v-model="add.name" :disabled="dialogType == 2 ? true : false"></el-input>
        </el-form-item>
        <el-form-item label="证书类型">
          <el-autocomplete clearable :disabled="dialogType == 2 ? true : false" class="inline-input" v-model="add.type"
            :fetch-suggestions="querySearch" @select="handleSelect" :label="options1.type" :value="options1.type">
            <template slot-scope="{ item }">
              <div class="name">{{ item.type }}</div>
            </template>
          </el-autocomplete>

          <!-- <el-input v-model="add.type" :disabled="dialogType == 2 ? true : false"></el-input> -->
        </el-form-item>
        <el-form-item label="证书有效期">
          <el-date-picker :disabled="dialogType == 2 ? true : false" v-model="add.time" value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="证书图片">
          <el-upload class="upload-demo" accept=".jpg,.jpeg,.png,.gif" :action=action list-type="picture-card"
            :on-preview="handlePreview" :on-success="handleSuccess" :on-remove="handleRemove"
            :disabled="dialogType == 2 ? true : false" :before-remove="beforeRemove" multiple :file-list="add.img">
            <!-- <el-button class="pubBtn" type="primary">点击上传</el-button> -->
            <i class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}" v-if="dialogType == 2">
              <img style="position: absolute;" class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog append-to-body :visible.sync="dialogVisibleImg">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item v-if="dialogType != 2">
          <el-button type="button" class="pubBtn2" @click="cancelAdd">取消{{dialogType == 0 ? '添加' : '修改'}}</el-button>
          <el-button type="button" class="pubBtn" style="width:98px;" @click="addSave">确定{{dialogType == 0 ? '添加' :
          '修改'}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <Service />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { indexCert, getType, createCert, infoCert, editCert, delCert } from "@/api"
import Service from '@/components/Service'
import { VUE_APP_BASE_API } from '@/config'
export default {
  components: {
    Service
  },
  data() {
    return {
      dialogType: 0,
      dialogTypeTitle: ['添加证书', '修改证书', '查看证书'],
      dialogImageUrl: '',
      dialogVisibleImg: false,
      action: VUE_APP_BASE_API + '/v1/common/file',
      add: {
        id: '',
        num: '',
        name: "",
        type: '',
        time: "",
        img: []
      },
      dialogVisible: false,
      ListArr: [],
      options1: [],
      options2: [
        // {
        //   label: '全部',
        //   value: 0
        // },
        {
          label: '未过期',
          value: 1
        },
        {
          label: '已过期',
          value: 2
        }
      ],
      value1: '',
      value2: '',
      page: 1,
      limit: 10,
      count: 0,
      user_id: this.$store.state.user.id,
    }
  },
  computed: {
    ...mapGetters([
      'is_admin_view'
    ]),
  },
  mounted() {
    this.indexCert()
    this.getType()
  },
  methods: {
    handleSelect(item) {
      // console.log(item, 131);
      this.add.type = item.type
    },
    querySearch(queryString, cb) {
      var restaurants = this.options1;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.type.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    AddCertificate() {
      this.dialogType = 0
      this.dialogVisible = true
    },
    cancelAdd() {
      this.add = {
        id: '',
        num: '',
        name: "",
        type: '',
        time: "",
        img: []
      }
      this.dialogVisible = false
    },
    getList() {
      this.indexCert()
    },
    getType() {
      getType({ user_id: this.user_id }).then(res => {
        this.options1 = res
        // console.log(res, 22)
      })
    },
    indexCert() {
      try {
        indexCert({
          user_id: this.user_id,
          page: this.page,
          limit: this.limit,
          status: this.value2,
          type: this.value1
        }).then(res => {
          // console.log(res, 11)
          this.count = res.count
          this.ListArr = res.list
        })
      } catch (e) {
        this.$message.error(e.message);
      }

    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.add.img = fileList
    },
    handlePreview(file) {
      // console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },
    handleSuccess(response, file, fileList) {
      // console.log(response, file, fileList, '上传成功');
      this.add.img = fileList
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    rowClick(row) {
    },
    //点击第几页
    async handleCurrentChange(indexCert) {
      try {
        this.page = indexCert
        this.indexCert()
      } catch (e) {
        this.$message.error(e.message);
      }
    },
    handleClose() {
      this.dialogVisible = false
    },
    async addSave() {
      let images = ''
      let image_name = ''
      this.add.img.map((res, index) => {
        if (res.response) {
          if (index == 0) {
            images += res.response.data.url
            image_name += res.response.data.name
          } else {
            images += ',' + res.response.data.url
            image_name += ',' + res.response.data.name
          }
        } else {
          if (index == 0) {
            images += res.url
            image_name += res.name
          } else {
            images += ',' + res.url
            image_name += ',' + res.name
          }
        }
      })
      try {
        if (this.dialogType == 0) {
          await createCert({
            user_id: this.user_id,
            number: this.add.num,
            name: this.add.name,
            type: this.add.type,
            term_time: this.add.time,
            images,
            image_name,
          })
        } else {
          await editCert({
            id: this.add.id,
            user_id: this.user_id,
            number: this.add.num,
            name: this.add.name,
            type: this.add.type,
            term_time: this.add.time,
            images,
            image_name
          })
        }

        this.indexCert()
        this.getType()
        this.dialogVisible = false
        this.$message.success("添加成功")
        this.add = {
          id: '',
          num: '',
          name: "",
          type: '',
          time: "",
          img: []
        }
      } catch (e) {
        this.$message.error(e.message)
      }


    },
    async deleteUser(id) {
      try {
        await delCert({
          user_id: this.user_id,
          id: id
        })
        this.indexCert()
        this.getType()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    see(id) {
      // console.log('查看')
      this.dialogType = 2
      this.dialogVisible = true
      this.infoCert(id)
    },
    set(id) {
      // console.log('修改')
      this.dialogType = 1
      this.dialogVisible = true
      this.infoCert(id)
    },
    infoCert(id) {
      infoCert(
        {
          user_id: this.user_id,
          id: id
        }
      ).then(res => {
        // console.log(res);
        this.add.id = res.id
        this.add.num = res.number
        this.add.name = res.name
        this.add.type = res.type
        this.add.time = res.term_time
        if (res.images.length > 0) {
          res.images.map((res_, index) => {
            // console.log(res_);
            let Obj = {
              name: res.image_name[index],
              url: res.images[index]
            }
            this.add.img.push(Obj)
          })
        }

      })
    }
  }
}
</script>

<style scoped lang="less">
::v-deep .el-autocomplete {
  width: 220px
}

.diff {
  color: #F05C6C;
}

::v-deep .delete {
  margin-left: 10px;

  span {
    color: #F05C6C;
  }
}

.input_item {
  margin-bottom: 20px;
}

::v-deep .el-dialog {
  .el-dialog__header {
    text-align: center;
  }

  .el-dialog__body {
    .el-form {
      .el-form-item {
        .el-form-item__label {
          text-align: left;
        }

        .el-form-item__content {
          .el-select {
            width: 100%;
          }
        }
      }

      //最后一个el-form-item的样式
      .el-form-item:last-child {
        margin-bottom: 0;
      }

      //倒数第二个el-form-item的样式
      .el-form-item:nth-last-child(2) {
        margin-bottom: 60px;
      }
    }
  }
}
</style>
